/*
 * Copyright 2022-2023 the original author(https://github.com/wj596)
 * 
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */
package org.jsets.fastboot.flowable.service.impl;

import java.util.List;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.jsets.fastboot.flowable.model.dto.InstanceQuery;
import org.jsets.fastboot.flowable.model.event.ProcessCompletedEvent;
import org.jsets.fastboot.flowable.service.IHistoricService;
import org.jsets.fastboot.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wangjie (https://github.com/wj596)
 * @date 2021.06.25 11:23
 */
@Slf4j
@Service
public class HistoricService implements IHistoricService {

	@Autowired
	private FlowEngineService flowEngine;

	@Override
	public Page<HistoricProcessInstance> selectHistoricProcessInstancePage(InstanceQuery criteria) {
		HistoricProcessInstanceQuery query = this.flowEngine.getHistoryService().createHistoricProcessInstanceQuery();
		if (StringUtils.notEmpty(criteria.getDefinitionKey())) {
			query.processDefinitionKey(criteria.getDefinitionKey());
		}
		if (StringUtils.notEmpty(criteria.getDefinitionName())) {
			query.processDefinitionName(criteria.getDefinitionName());
		}
		if (StringUtils.notEmpty(criteria.getBusinessKey())) {
			query.processInstanceBusinessKeyLike(criteria.getBusinessKey());
		}
		query.finished();
		query.orderByProcessInstanceEndTime().desc();

		Page<HistoricProcessInstance> page = new Page<HistoricProcessInstance>();
		page.setTotal(query.count());
		List<HistoricProcessInstance> list = query.listPage(criteria.getOffset(), criteria.getSize());
		page.setRecords(list);
		return page;
	}

	@Override
	@Subscribe
	public void transferHistoricProcessInstanceToElasticsearch(ProcessCompletedEvent completedEvent) {
        //IndexQuery indexQuery = new IndexQueryBuilder().withId(sampleEntity.getId()).withObject(sampleEntity).build();
        //elasticsearchTemplate.index(indexQuery);
	}
	
}